package com.x52im.rainbowchat.http.logic.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.x52im.rainbowchat.BaseConf;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MDepositRedirect extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doAll(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doAll(req, resp);
    }

    protected void doAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = req.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipayPublicCertPath是支付宝公钥证书路径，请去open.alipay.com对应应用下载。
        try {
            boolean flag = AlipaySignature.rsaCertCheckV1(params, BaseConf.getInstance().getALI_certPublicKey(), "UTF-8", "RSA2");
            if (flag) {
                // 验签成功,记录日志
                boolean b = new MDeposit().notifyBy(params);
                if (b) {
                    System.out.println("success");
                    resp.getWriter().print("success");
                } else {
                    System.out.println("error");
                    resp.getWriter().print("error");
                }
            } else {
                System.out.println("error");
                resp.getWriter().print("error");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
